package cfca.seal.web.action.crl;

import cfca.sadk.x509.certificate.X509CRL;
import cfca.seal.bean.AdminUser;
import cfca.seal.bean.OperationLog;
import cfca.seal.exception.CodeException;
import cfca.seal.mananger.CrlManager;
import cfca.seal.mananger.OperationLogManager;
import cfca.seal.system.Env;
import cfca.seal.util.FileUtil;
import cfca.seal.util.StringUtil;
import cfca.seal.util.TimeUtil;
import cfca.seal.web.service.OperationLogService;
import cfca.seal.web.system.SessionManager;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

@Controller
@RequestMapping({"/crl"})
public class CrlAction
{
  private static final Logger sysLog = LoggerFactory.getLogger("web_sys");

  private String applicationName = "CRL管理";

  @Resource
  private OperationLogService operationLogService;

  @RequestMapping({"/v_list"})
  public String input(String pageNo, ModelMap modelMap, HttpServletRequest request)
    throws CodeException
  {
    try
    {
      Map crlMap = new HashMap();

      File crlPath = new File(Env.crlResourceDir);
      for (File f : crlPath.listFiles()) {
        if ((f.isDirectory()) && (((String)getFileNameAndTime(f.listFiles()).get(0)).indexOf("crl.crl") != -1)) {
          crlMap.put(f.getName(), getFileNameAndTime(f.listFiles()));
        }
      }

      modelMap.put("crlMap", crlMap);
      return "sys/crl/input.html";
    } catch (Exception e) {
      sysLog.error("CRL查询出现系统错误", e);
      throw new CodeException("C0001", e);
    }
  }

  public List<String> getFileNameAndTime(File[] files)
  {
    List certList = new ArrayList();
    for (File file : files)
      if (file.getName().indexOf("svn") == -1)
      {
        String ctime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified()));
        certList.add(file.getName() + " (" + ctime + ")");
      }
    return certList;
  }

  @RequestMapping({"/o_file_delete"})
  public String deleteCRLFile(String fileName, HttpServletRequest request)
    throws CodeException
  {
    OperationLog operationLog = OperationLogManager.getInstance(request, this.applicationName, "删除", "crl.crl", "删除CRL文件", null);
    operationLog.setOrganizationId(SessionManager.getManager(request).getOrganizationId());
    try
    {
      sysLog.info("删除crl文件开始");
      File file = new File(Env.configDir + File.separator + "crl" + File.separator + fileName + "/");
      List<String> filePath = new ArrayList();
      filePath = FileUtil.showAllFiles(file, filePath, ".crl");

      if ((null != filePath) && (filePath.size() > 0)) {
        for (String path : filePath) {
          byte[] bCert = FileUtil.getBytesFromFile(new File(path));
          X509CRL x509CRL = new X509CRL(bCert);
          String issuerKey = StringUtil.formatIssuerKey(x509CRL.getIssuer());
          CrlManager.deleteX509CRL(issuerKey);
        }
      }

      if (file.exists()) {
        if (file.isDirectory())
          FileUtil.deleteDirectory(file.getAbsolutePath());
        else {
          FileUtil.deleteSingleFile(file.getAbsolutePath());
        }
        sysLog.info("删除crl文件成功");
      }
    } catch (Exception e) {
      operationLog.setResult(10);
      sysLog.error("删除crl异常", e);
      throw new CodeException("C0001", "删除crl异常", e);
    } finally {
      this.operationLogService.addOperationLog(operationLog);
    }

    return "redirect:/crl/v_list.do";
  }

  @RequestMapping({"/v_upload"})
  public String sysUpload(ModelMap map, HttpServletRequest request)
  {
    return "sys/crl/upload.html";
  }

  @RequestMapping({"/o_upload"})
  public String upload(@RequestParam("crlFile") CommonsMultipartFile crlFile, ModelMap modelMap, HttpServletRequest request)
    throws CodeException
  {
    OperationLog operationLog = OperationLogManager.getInstance(request, this.applicationName, "增加", "crl.crl", "上传CRL文件", null);
    operationLog.setOrganizationId(SessionManager.getManager(request).getOrganizationId());
    try
    {
      String str1;
      if (crlFile.isEmpty()) {
        modelMap.put("crlFileError", "请选择上传的crl文件。");
        return "sys/crl/upload.html";
      }if (!crlFile.getFileItem().getName().toLowerCase().endsWith(".crl")) {
        modelMap.put("crlFileError", "crl文件后缀必须是.crl格式。");
        return "sys/crl/upload.html";
      }
      sysLog.info("处理上传的crl文件开始");
      byte[] bCert = crlFile.getBytes();
      X509CRL x509CRL = new X509CRL(bCert);
      if ((!CrlManager.offline_crl) && (new Date().after(x509CRL.getNextUpdate()))) {
        modelMap.put("crlFileError", "配置要求检查crl,而上传的crl文件更新时间已经过期");
        return "sys/crl/upload.html";
      }
      String issuerKey = StringUtil.formatIssuerKey(x509CRL.getIssuer());
      File newFile = new File(Env.configDir + File.separator + "crl" + File.separator + issuerKey);
      if (!newFile.exists()) {
        newFile.mkdirs();
      }
      String fileName = Env.configDir + File.separator + "crl" + File.separator + issuerKey + File.separator + "crl.crl";
      Date time = TimeUtil.getCurrentTime();
      String tempFileName = fileName + time.getTime();
      FileUtil.saveDataToFile(bCert, tempFileName);

      FileUtil.replaceFile(fileName, tempFileName);

      CrlManager.updateCrlPool(issuerKey, x509CRL);
      sysLog.info("处理上传的crl文件成功");
      modelMap.put("successInfo", "上传CRL文件成功");
      return "redirect:/crl/v_list.do";
    } catch (Exception e) {
      operationLog.setResult(10);
      sysLog.error("处理crl文件错误", e);
      throw new CodeException("C0001", "处理crl文件错误");
    } finally {
      this.operationLogService.addOperationLog(operationLog);
    }
  }
}